﻿using CommunityToolkit.Mvvm.Input;
using MaterialDesignThemes.Wpf;
using Microsoft.Extensions.Caching.Distributed;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using UpperComputer.Application;

namespace UpperComputer.WPF.Entry.Common.Extensions
{
    public static class WindowExtensions
    {
        public static void OnMouseDownMethod(this Window window, MouseButtonEventArgs e)
        {
            if (e.ChangedButton == MouseButton.Left && e.ButtonState == MouseButtonState.Pressed)
            {
                window.DragMove();
            }
        }

        public static Task<object?> ShowCustomDialog(this object content, string dialogIdentifier)
        {
            return DialogHost.Show(content, dialogIdentifier);
        }

        public static void CheckPermissions(this IEnumerable<Button> buttonControls, string key)
        {
            ICollection<BaseMenuButtonResultDto> menuButtons = Furion.App.GetService<IDistributedCache>().Get<ICollection<BaseMenuButtonResultDto>>(key);
            if (menuButtons?.Count > 0)
            {
                foreach (Button buttonControl in buttonControls)
                {
                    buttonControl.Visibility = menuButtons.FirstOrDefault(mb => mb.Code.Equals(buttonControl.Name)) != null ? Visibility.Visible : Visibility.Collapsed;
                }
            }
        }

        public static void CancelToken(this IAsyncRelayCommand command)
        {
            if (command.IsRunning && !command.IsCancellationRequested)
            {
                command.Cancel();
            }
        }

        public static void CancelToken<T>(this IAsyncRelayCommand<T> command)
        {
            if (command.IsRunning && !command.IsCancellationRequested)
            {
                command.Cancel();
            }
        }
    }
}
